import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RunWith(SpringRunner.class)
@SpringBootTest
public class MemberServer {

    public static final String SECRET = "JKKLJOoasdlfj";
    public static final int calendarField = Calendar.DATE; //当前时间
    public static final int calendarInterval = 10;//存活时间,10天


    @Test
    public void testJWT() throws UnsupportedEncodingException {

        //JWT三大部分  头部 参数部分  签名

        Long user_id = 123456L;
        Date iatDate = new Date(); //当前时间
        // expire time
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(calendarField, calendarInterval);
        Date expiresDate = nowTime.getTime();

        // header Map 头信息
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HS256");
        map.put("typ", "JWT");

        // build token
        // param backups {iss:Service, aud:APP}
        String token = JWT.create().withHeader(map) // 创建头
                .withClaim("iss", "Service") // 默认参数
                .withClaim("aud", "APP").
                        withClaim("user_id", null == user_id ? null : user_id.toString()).
                withClaim("user_age",30)
                .withIssuedAt(iatDate) // sign time
                .withExpiresAt(expiresDate) // expire time  有效时间
                .sign(Algorithm.HMAC256(SECRET)); // signature

        System.err.println(token);

        System.out.println("----------------------");

        DecodedJWT jwt = null;
        try {
            JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
            jwt = verifier.verify(token);
        } catch (Exception e) {
            // e.printStackTrace();
            // token 校验失败, 抛出Token验证非法异常
        }
        System.out.println(jwt.getClaims());

        System.out.println("----------------------");

        Map<String, Claim> claims = jwt.getClaims();

        System.out.println("----null----");

        Claim user_id_claim = claims.get("user_id");
        Claim user_age_claim = claims.get("user_age");

        System.out.println(user_age_claim);

        System.err.println(user_id_claim);

//        if (null == user_id_claim || StringUtils.isEmpty(user_id_claim.asString())) {
//        }
        String s = user_id_claim.asString();

        System.err.println(user_age_claim.asLong());


        System.err.println(new Date());
        System.err.println(expiresDate);

    }
}
